package net.jeeeyul;

import java.text.MessageFormat;
import java.util.ArrayList;

import javax.jdo.PersistenceManager;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;

import com.google.appengine.api.channel.ChannelFailureException;
import com.google.appengine.api.channel.ChannelMessage;
import com.google.appengine.api.channel.ChannelService;
import com.google.appengine.api.channel.ChannelServiceFactory;

@PersistenceCapable
public class ChatRoom {
   public static ChatRoom get(PersistenceManager pm, String chatURL) {
      ChatRoom chatRoom = null;
      try {
         chatRoom = pm.getObjectById(ChatRoom.class, chatURL);
      } catch (Exception e) {
      }
      if (chatRoom == null) {
         chatRoom = new ChatRoom();
         chatRoom.setURL(chatURL);
         System.out.println("채팅룸 새로 생성: " + chatURL);
      }
      return chatRoom;
   }

   @PrimaryKey
   @Persistent
   private String url;

   @Persistent
   private ArrayList<String> clients = new ArrayList<String>();

   public void addClient(String clientId) {
      if (clients.contains(clientId)) {
         return;
      }
      clients.add(clientId);
      System.out.println(url + "에 " + clientId + " 사용자가 추가됨.");
   }

   public String getURL() {
      return url;
   }

   public void removeClient(String clientId) {
      clients.remove(clientId);
   }
   
   public static void main(String[] args) {

      String json = MessageFormat.format(
            "'{'\"sender\" : \"{0}\", \"message\" : \"{1}\" '}'", "Aa", "bb");
      System.out.println(json);
      
      System.out.println(json);
   }

   public void sendMessage(String sender, String message) {
      sender = sender.replace("\"", "\\\"");
      message = message.replace("\"", "\\\"");

      String json = MessageFormat.format(
            "'{'\"sender\" : \"{0}\", \"message\" : \"{1}\" '}'", sender, message);
      System.out.println(json);

      ChannelService channelService = ChannelServiceFactory.getChannelService();
      String[] clientArray = clients.toArray(new String[clients.size()]);
      for (String client : clientArray) {
         try {
            channelService.sendMessage(new ChannelMessage(client, json));
         } catch (ChannelFailureException e) {
            clients.remove(client);
         }
         System.out.println(client);
      }
      System.out.println(clients.size());
   }

   public void setURL(String url) {
      this.url = url;
   }
}
